package demo.jdbc;
//JDBC访问数据库
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "ServletJDBC01", value = "/ServletJDBC01")
public class ServletJDBC01 extends HttpServlet {
    String databaseName = "EMP"; // 数据库名
    String USER = "root"; // 使用管理员账号启动
    String PSD = "Aa123-456"; // 数据库密码
//    String DB_URL = "jdbc:mysql://39.108.52.113:3306/" + databaseName;
//          + "?useSSL=false&&allowPublicKeyRetrieval=true&serverTimezone=UTC"; // MySQL8.0以下不用写注释行

    // MySQL8.0以下版本 - JDBC 驱动名及数据库 URL
    static final String DB_URL = "jdbc:mysql://39.108.52.113:3306/EMP";
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PSD);

            // 执行查询
            System.out.println("实例化Statement对象...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT id, first, last, age FROM Employees";
            ResultSet rs = stmt.executeQuery(sql);

            // 展开结果集数据库
            while (rs.next()) {
                int id = rs.getInt("id");
                int age = rs.getInt("age");
                String first = rs.getString("first");
                String last = rs.getString("last");

                PrintWriter out = response.getWriter();
                // 输出数据
                out.print("ID: " + id);
                out.print(", 年龄: " + age);
                out.print(", 姓: " + first);
                out.print(", 名: " + last);
                out.print("</br>");
            }
            // 完成后关闭
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (stmt != null) stmt.close();
            } catch (SQLException se2) {

            } // 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");
    }
}

